package com.zhu.service.impl;

import com.zhu.mapper.UserMapper;
import com.zhu.pojo.entity.Result;
import com.zhu.pojo.entity.User;
import com.zhu.properties.JwtProperties;
import com.zhu.service.UserService;
import com.zhu.utils.JwtUtil;
import com.zhu.utils.ThreadLocalUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByUserName(String username) {
        return userMapper.findByUserName(username);
    }

    @Override
    public Boolean register(String username, String password) {
        User user = userMapper.findByUserName(username);
        if (user == null) {
            String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
            userMapper.add(username, md5Password);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public User login(String username, String password) {
        return userMapper.findByUserName(username);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updateAvatar(avatarUrl, id);
    }

    @Override
    public void updatePwd(String pwd) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updatePwd(DigestUtils.md5DigestAsHex(pwd.getBytes()), id);
    }
}
